package com.example.util;

import com.example.common.HttpHandlerModel;
import com.example.common.HttpServerStart;
import com.example.factory.HttpHandlerFactory;
import com.example.proxy.MethodProxy;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname AppliationStart
 * @Description TODO
 * @Date 2023/4/25 14:13
 * @Created by XiongXiong
 * @Author: X.I.O
 *
 * 基于系统的httpServer代码实现的
 */
public class AppliationStart {

    /**
     * web接口
     */
    private static Map<String, HttpHandlerModel> handlersModelMaps;

    public static void run(String[] args,Class<?> cls){
        try {
            ClassScanUtils.searchClass(cls);
            ClassScanUtils.scanClass(cls);
            ApplicationContent.start();
            Map<String, MethodProxy>  methodProxyMap=ApplicationContent.getWebMethodProxy();
            Map<String,HttpHandlerModel> httpHandlerModelMap=getHttpHandlerModelbyMethodProxy(methodProxyMap);
            //读取配置
            Map<String,String> config=ApplicationContent.getConfig();
            String port=config.get("server.port");
            HttpServerStart httpServerStart=new HttpServerStart(Integer.parseInt(port));
            addWebPath(httpServerStart,httpHandlerModelMap);
            addHttpContext(httpServerStart);
            httpServerStart.start();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Map<String,HttpHandlerModel> getHttpHandlerModelbyMethodProxy(Map<String, MethodProxy> map){
        Map<String,HttpHandlerModel> httpHandlerModelMap = new HashMap<>();
        for (Map.Entry<String, MethodProxy> entry : map.entrySet()) {
            httpHandlerModelMap.put(entry.getKey(),HttpHandlerFactory.getHttpHandlerModel(entry.getValue()));
        }
        return httpHandlerModelMap;
    }


    public static void addWebPath(HttpServerStart httpServerStart,Map<String,HttpHandlerModel> httpHandlerModels){
        for(Map.Entry< String, HttpHandlerModel> httpHandlerModel:httpHandlerModels.entrySet()){
            String path = httpHandlerModel.getKey();
            HttpHandlerModel http = httpHandlerModel.getValue();
            LogUtils.info("添加接口:"+path);
            httpServerStart.addHttpHandler(path, http);
        }
    }


    /**
     * 添加静态资源
     * @param httpServerStart
     */
    public static void addHttpContext(HttpServerStart httpServerStart) throws Exception {
        httpServerStart.addHttpContext("/");
    }


}
